package com.hjrpc.babyyamall.product.exception;

import com.hjrpc.common.exception.BizCodeEnum;
import com.hjrpc.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@Slf4j
@RestControllerAdvice(basePackages = "com.hjrpc.babyyamall.product.controller")
public class ProductExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handlerArgumentValidException(MethodArgumentNotValidException e) {

        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", e.getBindingResult().getFieldErrors().stream()
                .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage)));//简写
//                .collect(Collectors.toMap(x -> x.getField(), x -> x.getDefaultMessage())));
    }

    @ExceptionHandler(value = Throwable.class)
    public R handlerGlobalException(Throwable e) {
        log.error("异常", e);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION);
    }
}
